package com.cndw.kungfu.model.pvp.war;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.activity.domain.CrossServer;
import com.cndw.kungfu.model.pvp.api.ApiCore;

/**
 * 跨服处理器
 * 
 * @author fantadust [9677889@qq.com]
 * @date 2012-7-20 上午12:07:20
 */
public class WarCrossPross implements Runnable {

	public static Map<Integer, WarCrossPross> crossTask = new ConcurrentHashMap<Integer, WarCrossPross>();

	private ScheduledFuture<?> task;

	private int area;

	private WarCrossPross(int area) {
		this.area = area;
	}

	@Override
	public void run() {
		try {
			if (WarData.getInstance().getStep() < 3 && ConstantsConfig.isLocalHost()) {//本地时候跨服没完成
				return;
			}
			WarCrossData warCrossData = WarCoreCenter.getCrossData(area);
			warCrossData.runBoss();

			if (warCrossData.getStep() >= 3) {
				task.cancel(false);
				crossTask.remove(area);
				LogUtil.getMain().info("cross task stop " + area);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public ScheduledFuture<?> getTask() {
		return task;
	}

	public void setTask(ScheduledFuture<?> task) {
		this.task = task;
	}

	public static synchronized void runBoss() {

		if (!ApiCore.isCrossServer()) {
			return;
		}
		int currentTime = TimeProcesser.getUnixTime();
		int diff = WarConfig.getCrossBegin() + WarConfig.eliminateBegin - currentTime;
		for (CrossServer e : CrossServer.getAll()) {
			if (e.getType() <= 0) {
				continue;
			}
			if (crossTask.containsKey(e.getType())) {
				continue;
			}

			WarCrossData warCrossData = WarCoreCenter.getCrossData(e.getType());
			warCrossData.checkCycle(e.getType());
			if (warCrossData.getStep() >= 3) {
				continue;
			}

			WarCrossPross warCrossPross = new WarCrossPross(e.getType());

			ScheduledFuture<?> task = Context.getTimerServer().scheduleAtFixedRate(warCrossPross, diff <= 0 ? 1 : diff, 10);
			warCrossPross.setTask(task);
			crossTask.put(e.getType(), warCrossPross);

			LogUtil.getMain().debug("war cross " + e.getType() + " begin " + diff);
		}

	}

}
